package net.projects.pro2_atm;

import com.google.gson.Gson;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BankTask implements Runnable{

    private Socket socket;
    private Bank b;

    public BankTask(Socket socket, Bank b) {
        this.socket = socket;
        this.b = b;
    }

    @Override
    public void run() {
        try(
                Socket socket = this.socket;
                Scanner reader = new Scanner(socket.getInputStream());
                PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
        ){
            while (true){
                Jsonmodel<BankAccount> jm=new Jsonmodel<>();
                String command=reader.next();
                BankAccount ba=null;
                if ("DEPOSIT".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.deposit(id,money);
                }else if ("WITHDRAW".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba= b.withdraw(id,money);
                }else if ("BALANCE".equals(command)){
                    int id=reader.nextInt();
                    ba = b.serch(id);
                }else if ("QUIT".equals(command)){
                   pw.println("客户要求退出ATM"+socket.getRemoteSocketAddress());
                    break;
                }else {
                    jm.setCode(0);
                    jm.setErrorMessge("命令错误");
                    Gson g=new Gson();
                    String json = g.toJson(jm);
                    pw.println(json);
                    pw.flush();
                    continue;
                }

                jm.setCode(1);
                jm.setObj(ba);
                Gson g=new Gson();
                String json = g.toJson(jm);
                pw.println(json);
                pw.flush();
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
